import os

class AliasManager:
    """
    Command aliases are shorthand for shell commands
    This class contains the basic stuff for reading and saving commmand aliases
    These aliases are in the profile directory(the profile directory is .glassbead
    in the users home folder) in a file called aliases.py which contains a
    python dictionary named ALIASES.
    This dictionary's keys are alias names and values are any string of valid
    shell commands of your liking

    """
    def __init__(self):
        self.ALIASES={}
        self.SORTEDALIASES=[]
        self.readaliases()
        self.sortaliases()

    def readaliases(self):
        ConfigError=False
        fname = os.path.join("~", ".glassbead", "aliases.py")
        fname = os.path.expanduser(fname)
        if os.path.exists(fname):
            try:
                globs={}
                execfile(fname, {}, globs)
            except Exception, v:
                ConfigError=True
        else:
            ConfigError=True

        if not ConfigError:
           self.ALIASES=globs.get("ALIASES")
           

    def writealiases(self):
        ConfigError=False
        fname = os.path.join("~", ".glassbead", "aliases.py")
        fname = os.path.expanduser(fname)
        if os.path.exists(fname):
            try:
                file=open(fname,"r+")
                file.write("ALIASES="+str(self.ALIASES))
            except Exception, v:
                ConfigError=True
        else:
            file=open(fname,"w")
            file.write("ALIASES="+str(self.ALIASES))
            ConfigError=True

           
    def getcommandforalias(self,alias):
        if self.ALIASES.has_key(alias):
            return self.ALIASES[alias]
        else:
            return ""

    def findclosestalias(self,str):
            for alias in self.SORTEDALIASES:
                if alias.startswith(str):
                    return alias
            return ""
        
    def findclosestaliaslist(self,str):
            list=[]
            for alias in self.SORTEDALIASES:
                if alias.startswith(str):
                    list.append(alias)
            return list

    def sortaliases(self):
        """
        Sorts the aliases based on their lengths
        """
        self.SORTEDALIASES=self.ALIASES.keys()
        self.SORTEDALIASES.sort(key=len)
        

if __name__=="__main__":
    mgr=AliasManager()
    mgr.ALIASES['filebrowser']='nautilus'
    mgr.ALIASES['file']='nautilus'
    mgr.ALIASES['filer']='nautilus'
    #mgr.writealiases()
    #print mgr.getcommandforalias('filebrowser')
    mgr.sortaliases()
    print mgr.findclosestaliaslist('f')
    print mgr.findclosestalias('')